{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit Scene;

interface

uses
  Classes, SysUtils, superobject, MiscUtils;

type
  TShapeId = type String;
  TSuperObjectList = TGenericList<ISuperObject>;

  TScene = class
  private
    FCurrentFrame: ISuperObject;
    FChanged: Boolean;
    function GetShapes(const Id: TShapeId): ISuperObject;
  public
    constructor Create;
    function Update(const Id: TShapeId; var Value: ISuperObject): Boolean;
    function GetKind(const Shape: ISuperObject): TKind;
    procedure ActionListExecuteFilter(Action: TBasicAction; var Handled: Boolean);
    procedure ApplyDelta(const Delta: ISuperObject);
    procedure ResetChanged;

    property Changed: Boolean read FChanged;
    property Shapes[const Id: TShapeId]: ISuperObject read GetShapes; default;
  end;

implementation

const
  KIND_PROPERTY = 'kind';
  
{ TScene }

constructor TScene.Create;
begin
  inherited;
  FCurrentFrame := SO;
end;

function TScene.GetShapes(const Id: TShapeId): ISuperObject;
begin
  Result := FCurrentFrame.AsObject[Id];
  if Result = nil then
    raise Exception.CreateFmt('Shape "%s" not found.', [Id]);
end;

function TScene.Update(const Id: TShapeId; var Value: ISuperObject): Boolean;
var
  NewValue: ISuperObject;
begin
  NewValue := GetShapes(Id);
  Result := Value <> NewValue;
  if Result then
    Value := NewValue;
end;

function TScene.GetKind(const Shape: ISuperObject): TKind;
begin
  Result := StringToKind(Shape.S[KIND_PROPERTY]);
end;

procedure TScene.ActionListExecuteFilter(Action: TBasicAction; var Handled: Boolean);
begin
  if FChanged then
    Handled := TRUE;
end;

procedure TScene.ResetChanged;
begin
  FChanged := FALSE;
end;

procedure TScene.ApplyDelta(const Delta: ISuperObject);
var
  Item: TSuperAvlEntry;
  Id: ISuperObject;
begin
  for Item in Delta['changed'].AsObject do
    FCurrentFrame[Item.Name] := Item.Value;

  for Id in Delta['deleted'] do
    FCurrentFrame.Delete(Id.AsString);

  FChanged := TRUE;
end;

end.
